/**
 * 
 */
package com.xored.glance.internal.core;

import org.eclipse.core.runtime.ListenerList;

import com.xored.glance.core.ISourceListener;
import com.xored.glance.core.ITextProvider;
import com.xored.glance.core.ITextSource;

/**
 * @author Yuri Strot
 * 
 */
public class CompositeSourceListener implements ISourceListener, ITextProvider {

	public CompositeSourceListener(ITextProvider[] providers) {
		this.providers = providers;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.xored.glance.core.ISourceListener#sourceChanged(com.xored.glance.
	 * core.ITextSource)
	 */
	public void sourceChanged(ITextSource source) {
		ITextSource newSource = getSource();
		if (newSource != this.source) {
			this.source = newSource;
			Object[] objects = listeners.getListeners();
			for (Object object : objects) {
				ISourceListener listener = (ISourceListener) object;
				listener.sourceChanged(newSource);
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.xored.glance.core.ITextProvider#addSourceListener(com.xored.glance
	 * .core.ISourceListener)
	 */
	public void addSourceListener(ISourceListener listener) {
		assert listener != null;
		if (listeners.size() == 0) {
			for (ITextProvider provider : providers) {
				provider.addSourceListener(this);
			}
		}
		listeners.add(listener);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.xored.glance.core.ITextProvider#getSource()
	 */
	public ITextSource getSource() {
		for (ITextProvider provider : providers) {
			ITextSource source = provider.getSource();
			if (source != null)
				return source;
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.xored.glance.core.ITextProvider#removeSourceListener(com.xored.glance
	 * .core.ISourceListener)
	 */
	public void removeSourceListener(ISourceListener listener) {
		listeners.remove(listener);
		if (listeners.size() == 0) {
			for (ITextProvider provider : providers) {
				provider.removeSourceListener(this);
			}
		}
	}

	private ITextSource source;
	private ListenerList listeners = new ListenerList();
	private ITextProvider[] providers;

}
